package com.yc.sole.system.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.common.constant.CacheConstant;
import com.yc.sole.framework.redis.RedissonService;
import com.yc.sole.system.dto.ConfigDto;
import com.yc.sole.system.entity.Config;
import com.yc.sole.system.mapper.ConfigMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2024-01-23
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ConfigRepository extends ServiceImpl<ConfigMapper, Config> {

    private final RedissonService redissonService;

    /**
     * 新增
     *
     * @param configDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveConfig(ConfigDto configDto) {
        Config entity = new Config();
        BeanUtil.copyProperties(configDto, entity);
        this.save(entity);
        redissonService.hRemoveAll(CacheConstant.CONFIG_PREFIX);
    }

    /**
     * 通过Id修改
     *
     * @param configDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateConfigById(ConfigDto configDto) {
        Config entity = new Config();
        BeanUtil.copyProperties(configDto, entity);
        this.updateById(entity);
        redissonService.hRemoveAll(CacheConstant.CONFIG_PREFIX);
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteConfigByIds(Collection<String> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 根据id获取
     *
     * @param ids
     * @return RestResult
     */
    public List<ConfigDto> selectConfigByIds(Set<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(this.listByIds(ids), ConfigDto.class);
    }

    /**
     * 查询配置
     *
     * @return RestResult
     */
    public ConfigDto selectConfig() {
        return redissonService.hCache(CacheConstant.CONFIG_PREFIX, "CONFIG", () -> {
            List<Config> list = this.list();
            if (CollUtil.isEmpty(list)) {
                return null;
            }
            return BeanUtil.copyProperties(list.get(0), ConfigDto.class);
        });
    }
}
